from setux.core.package import CommonPackager
from setux.targets import Local
from setux.logger import info, error


# pylint: disable=no-member


class Distro(CommonPackager):
    manager = 'flatpak'

    pkgmap = dict(
        kicad    = 'org.kicad.KiCad',
        freecad  = 'org.freecadweb.FreeCAD',
        openscad = 'org.openscad.OpenSCAD',
	blanket  = 'com.rafaelmardojai.Blanket',
	flatseal = 'com.github.tchx84.Flatseal',
    )

    def do_init(self):
        ret, out, err = self.run('flatpak --version')
        if ret==0:
            ret, out, err = self.run(
                'flatpak run com.github.tchx84.Flatseal -h',
                report = 'quiet',
            )
            if ret!=0:
                self.do_install('flatseal')
            return
        self.target.Package.install('flatpak')
        self.run('''
            flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
        ''')
        info(' * REBOOT needed *')

    def do_install(self, pkg, ver=None):
        ret, out, err = self.run(f'flatpak install -y flathub {pkg}')

    def do_installed(self, pattern=None):
        ret, out, err = self.run('flatpak list --columns=application,version')
        for line in out[1:]:
            try:
                n, v  = line.split()
                yield n.strip(), v.strip()
            except: pass

    def get_pkg_list(self):
        local = Local(outdir='/tmp')
        dst = '/tmp/setux/flatpak.packages'
        try:
            fil = local.file(dst)
            if fil.age is not None:
                if fil.age < 10: return
        except FileNotFoundError: pass

	# flatpak search --columns=description
        ret, out, err = self.run(
            'flatpak remote-ls flathub',
            report = 'quiet',
        )
        if ret!=0:
            error('\n'.join(out))
            return

        with open(dst, 'w') as pkg:
            for line in out:
                _desc, app, ver, _inst = line.split('\t')
                if ver.strip():
                    pkg.write(f'{app} {ver}\n')

    def do_installable(self, pattern=None):
        dst = '/tmp/setux/flatpak.packages'
        self.get_pkg_list()
        for line in open(dst):
            yield line.strip().split()

    def do_remove(self, pkg):
        self.run(f'flatpak uninstall -y {pkg}')

    def do_cleanup(self):
        raise NotImplemented

    def do_update(self):
        raise NotImplemented

